﻿using TuLing.Blazor.Dto;
using TulingMember.Core;

namespace TuLing.Blazor.Services
{
    public class ProductCategoryService : BaseService
    {
        public ProductCategoryService(DefaultDbContext context) : base(context) { }

        /// <summary>
        /// 检索分类
        /// </summary>
        public List<ProductCategory> SearchProductType(BaseInput input)
        {
            return input.keyword == null
            ? _context.ProductTypes.ToList()
                : _context.ProductTypes.Where(m => m.Name.Contains(input.keyword)).ToList();
        }

        /// <summary>
        /// 获取分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ProductCategory? Get(long id)
        {
            return _context.ProductTypes.FirstOrDefault(m => m.Id == id);
        }

        /// <summary>
        /// 分类树
        /// </summary>
        /// <returns></returns>
        public List<TreeProductTypeDto> GetTree()
        {
            var list = _context.ProductTypes.Select(u =>
            new TreeProductTypeDto()
            {
                Id = u.Id,
                Name = u.Name,
                ParentId = u.ParentId
            }).ToList();
            return BuildTree(list);
        }

        private List<TreeProductTypeDto> BuildTree(List<TreeProductTypeDto> allNodes)
        {
            var rootNodes = new List<TreeProductTypeDto>();
            // 构建节点字典，方便查找
            var nodeDict = new Dictionary<long, TreeProductTypeDto>();

            foreach (var node in allNodes)
            {
                nodeDict[node.Id] = node;
            }

            foreach (var node in allNodes)
            {
                if (node.ParentId == 0)
                    // 根节点
                    rootNodes.Add(node);
                else if (nodeDict.TryGetValue(node.ParentId, out var parent))
                {
                    // 找到父节点并添加子节点
                    parent.Children.Add(node);
                }
            }
            return rootNodes;
        }

        /// <summary>
        /// 获取商品分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public TreeProductTypeDto GetTypeDto(long id)
        {
            var category = _context.ProductTypes.FirstOrDefault(m => m.Id == id);
            if (category == null)
            {
                throw new Exception("商品分类不存在。");
            }
            var dto = new TreeProductTypeDto
            {
                Id = category.Id,
                Name = category.Name,
                ParentId = category.ParentId
            };
            var list = _context.ProductTypes.Where(m => m.ParentId == id).ToList();
            foreach (var item in list)
            {
                dto.Children.Add(new TreeProductTypeDto
                {
                    Id = item.Id,
                    Name = item.Name,
                    ParentId = item.ParentId
                });
            }
            return dto;
        }

        /// <summary>
        /// 检查分类是否存在
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool IsExist(ProductCategory input)
        {
            return _context.ProductTypes.Any(m => m.Name.Equals(input.Name) && m.Id != input.Id);
        }

        /// <summary>
        /// 保存分类
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ProductCategory Save(ProductCategory input)
        {
            if (input.Id > 0)
            {
                _context.ProductTypes.Update(input);
                _context.SaveChanges();
                return input;
            }
            else
            {
                _context.ProductTypes.Add(input);
                _context.SaveChanges();
                return _context.ProductTypes.OrderBy(s => s.Id).Last();
            }
        }

        /// <summary>
        /// 删除分类
        /// </summary>  
        public void Delete(long id)
        {
            var pType = _context.ProductTypes.FirstOrDefault(m => m.Id == id);
            if (pType == null)
            {
                throw new Exception("商品分类不存在。");
            }
            else
            {
                _context.ProductTypes.Remove(pType);
                _context.SaveChanges();
            }
        }
    }
}
